﻿namespace Deppton.Mobile.Views
{
    using System;
    using Deppton.Model;

    public partial class SurveyForm : DepptonForm
    {
        public SurveyForm(IServicesPortfolio servicesPortfolio, string surveyId)
        {
            this.SurveyId = surveyId;
            this.ServicesPortfolio = servicesPortfolio;

            this.InitializeComponent();
            this.UpdateInformation();
        }

        public string SurveyId
        {
            get;
            private set;
        }

        public IServicesPortfolio ServicesPortfolio
        {
            get;
            set;
        }

        private void UpdateInformation()
        {
            var survey = this.ServicesPortfolio.SurveysStorageService.Retrieve(this.SurveyId);
            this.WorkItemDescriptionLabel.Text = survey.Description;
            this.StatusLabel.Text = survey.Status.ToFriendlyStatus();

            this.ContinueActionMenuItem.Enabled = survey.Status == SurveyStatus.Pending;
            this.ReviewActionMenuItem.Enabled = survey.Status == SurveyStatus.Completed;

            this.ResultLabel.Text = EvaluateSurveyResults(survey);
        }

        private string EvaluateSurveyResults(Survey survey)
        {
            var surveyDefinition = this.ServicesPortfolio.SurveyDefinitionsStorageService.RetrieveSurveyDefinition(survey.SurveyDefinitionId);
            string result = string.Empty;

            foreach (var resultDefinition in surveyDefinition.ResultDefinitions)
            {
                if (surveyDefinition.RulesetDefinitions[resultDefinition.Ruleset].Evaluate(
                    identifier => SurveyController.EvaluateQuestionValue(survey, identifier),
                    identifier => SurveyController.EvaluateQuestionMetadata(survey, identifier)))
                {
                    result += (result == string.Empty ? "" : ", ") + resultDefinition.Result;
                }
            };

            return result;
        }

        private void BackMenuItemClick(object sender, System.EventArgs e)
        {
            this.Close();
        }

        private void ContinueActionMenuItemClick(object sender, System.EventArgs e)
        {
            new SurveyController(this.ServicesPortfolio).RunSurvey(this.SurveyId);

            this.UpdateInformation();
        }

        private void ReviewActionMenuItemClick(object sender, EventArgs e)
        {
            new SurveyController(this.ServicesPortfolio).ReviewSurvey(this.SurveyId);
        }
    }
}
